from django import forms
from .models import Food, FoodCategory
from .models import StorageLocation
import datetime
from django.utils.timezone import timedelta

class FoodForm(forms.ModelForm):
    # unit = forms.CharField(  # 新增unit字段
    #     label="单位",
    #     widget=forms.TextInput(attrs={'class': 'form-control'})
    # )

    class Meta:
        model = Food
        fields = ['name', 'production_date', 'shelf_life', 'shelf_life_unit',
                 'image', 'quantity_status', 'location', 'category']
        widgets = {
            'production_date': forms.DateInput(attrs={
                'type': 'date',
                'class': 'form-control',
                'placeholder': '选择生产日期',
                'required': 'required' 
            }),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 隐藏quantity字段
        self.fields['quantity'] = forms.CharField(
            widget=forms.HiddenInput(),
            required=False
        )

    def save(self, commit=True):
        instance = super().save(commit=False)
        # 保留原始quantity值
        if self.instance and self.instance.pk:
            instance.quantity = self.instance.quantity
        # return super().save(commit)
        
        # 增加必要字段验证
        if not instance.production_date:
            raise ValueError("生产日期为必填项")
        if not instance.shelf_life:
            raise ValueError("保质期为必填项")

        try:
            shelf_days = int(instance.shelf_life)
            if instance.shelf_life_unit == 'month':
                delta = timedelta(days=shelf_days*30)
            elif instance.shelf_life_unit == 'year':
                delta = timedelta(days=shelf_days*365)
            else:  # 天
                delta = timedelta(days=shelf_days)
                
            instance.expiration_date = instance.production_date + delta
        except TypeError as e:
            raise ValueError("无效的保质期参数") from e

        if commit:
            instance.save(force_insert=False, force_update=False)
        return instance

class CategoryForm(forms.ModelForm):
    class Meta:
        model = FoodCategory
        fields = ['name', 'description']

class StorageLocationForm(forms.ModelForm):
    class Meta:
        model = StorageLocation
        # 移除了level字段，因为该字段应由系统自动计算
        fields = ['name', 'parent']
        exclude = ['level', 'user']  # 新增排除字段